package com.youi.util;

import javax.servlet.http.HttpServletRequest;

import com.youi.model.AddressInfo;
import com.youi.model.IpAddress;

/**
 * ip地址工具
 * @author  erdong.Chan
 *
 */
public class IpUtil {
	
	/**获取ip所在地址url*/
	public static String urlStr="http://ip.taobao.com/service/getIpInfo.php";

	/**
	 * 获取ip地址
	 * @param request
	 * @return
	 */
	public static String getIpAddr(HttpServletRequest request) {  
	    String ip = request.getHeader("x-forwarded-for");  
	    if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {  
	        ip = request.getHeader("PRoxy-Client-IP");  
	    }  
	    if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {  
	        ip = request.getHeader("WL-Proxy-Client-IP");  
	    }  
	    if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {  
	        ip = request.getRemoteAddr();  
	    }  
	    return ip;  
	}  
	
	/**
	 * 获取ip所在地址
	 * @param ip
	 * @return
	 */
	 public static String  getAddresses(String ip){
		String address="";
		if (ip!=null&&ip.length()>0) {
			String responseStr=RequestUtil.Action(urlStr,RequestUtil.POST, "ip="+ip, "获取ip所在地址",null);
			if (responseStr!=null&&responseStr.length()>0) {
				IpAddress ipAddress=JsonUtil.fromJson(responseStr, IpAddress.class);
				if (ipAddress.getData()!=null) {
					AddressInfo addressInfo=ipAddress.getData();
					address=addressInfo.getCountry()+addressInfo.getRegion()+addressInfo.getCity();
				}
			}
		}
		return  address;
	 }

	 public static void main(String[] args) {
		 System.out.println(getAddresses("121.33.146.43"));
	}
}
